/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.ap.entity.ProcurementApplication;
import com.jeeplus.modules.ap.mapper.ProcurementApplicationMapper;
import com.jeeplus.modules.ap.entity.ApplicationDetil;
import com.jeeplus.modules.ap.mapper.ApplicationDetilMapper;

/**
 * 采购申请Service
 * @author LCH
 * @version 2018-12-12
 */
@Service
@Transactional(readOnly = true)
public class ProcurementApplicationService extends CrudService<ProcurementApplicationMapper, ProcurementApplication> {

	@Autowired
	private ApplicationDetilMapper applicationDetilMapper;
	
	public ProcurementApplication get(String id) {
		ProcurementApplication procurementApplication = super.get(id);
		procurementApplication.setApplicationDetilList(applicationDetilMapper.findList(new ApplicationDetil(procurementApplication)));
		return procurementApplication;
	}
	
	public List<ProcurementApplication> findList(ProcurementApplication procurementApplication) {
		return super.findList(procurementApplication);
	}
	
	public Page<ProcurementApplication> findPage(Page<ProcurementApplication> page, ProcurementApplication procurementApplication) {
		return super.findPage(page, procurementApplication);
	}
	
	@Transactional(readOnly = false)
	public void save(ProcurementApplication procurementApplication) {
		super.save(procurementApplication);
		for (ApplicationDetil applicationDetil : procurementApplication.getApplicationDetilList()){
			if (applicationDetil.getId() == null){
				continue;
			}
			if (ApplicationDetil.DEL_FLAG_NORMAL.equals(applicationDetil.getDelFlag())){
				if (StringUtils.isBlank(applicationDetil.getId())){
					applicationDetil.setApplication(procurementApplication);
					applicationDetil.preInsert();
					applicationDetilMapper.insert(applicationDetil);
				}else{
					applicationDetil.preUpdate();
					applicationDetilMapper.update(applicationDetil);
				}
			}else{
				applicationDetilMapper.delete(applicationDetil);
			}
		}
	}
	
	@Transactional(readOnly = false)
	public void delete(ProcurementApplication procurementApplication) {
		super.delete(procurementApplication);
		applicationDetilMapper.delete(new ApplicationDetil(procurementApplication));
	}
	
}